package com.linran.javaweb.interceptor;

import com.linran.javaweb.util.Converter;
import com.linran.javaweb.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.linran.javaweb.util.PageUtil.PAGE_NO;
import static com.linran.javaweb.util.PageUtil.PAGE_SIZE;

/**
 * 分页拦截器
 *
 * @author lin
 * @date 2020-06-20 14:20
 */
@Slf4j
public class PageInterceptor implements HandlerInterceptor {
    private static final String GET = "GET";
    private static final String POST = "POST";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Integer pageNo = null;
        Integer pageSize = null;
        //GET处理
        if (GET.equals(request.getMethod())) {
            pageNo = Converter.getAsInteger(request.getParameter(PAGE_NO));
            pageSize = Converter.getAsInteger(request.getParameter(PAGE_SIZE));
        //POST处理 这种方式有问题，因为流只能处理一次，后续controller操作会导致读取不到body
        }
        PageUtil.setPageParam(pageNo, pageSize);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        PageUtil.clear();
    }
}
